package com.lottery.www.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${token.expire}")
    private Long expire;

    /**
     * 用户信息和token存入redis
     * @param loginName ： 登录账号
     * @param token
     */
    public void setTokenToRedis(String loginName, String token){
        redisTemplate.opsForValue().set(KeyValueContent.TOKEN_USER_PREFIX+loginName,token,expire, TimeUnit.DAYS);
        //redisTemplate.opsForValue().set(KeyValueContent.TOKEN_USER_PREFIX+KeyValueContent.USER_ROLES_PREFIX+currentUser.getUserId(),currentUser.getRoleList(),expire, TimeUnit.DAYS);
    }

    public String getTokenFromRedis(String loginName){
        Object o = redisTemplate.opsForValue().get(KeyValueContent.TOKEN_USER_PREFIX + loginName);
        if(o==null){
            return null;
        }
        return (String) o;
    }

    public void removeKey(String key){
        Boolean delete = redisTemplate.delete(KeyValueContent.TOKEN_USER_PREFIX+key);
        System.out.println("=================删除"+key+"的结果："+delete);
    }

    public JSONArray getJsonArrayFromRedis(String key){
        Object o = redisTemplate.opsForValue().get(KeyValueContent.TOKEN_USER_PREFIX + key);
        //System.out.println("ooooooooooooooooooooooooooo:"+o);
        //System.out.println("key........:"+key);
        if(o==null){
            return null;
        }
        return JSON.parseArray(String.valueOf(o));
    }

    public void addOrAppend(String key,Object obj){
        JSONArray jsonArray = this.getJsonArrayFromRedis(key);
        /*obj = "hello";
        String tokenFromRedis = this.getTokenFromRedis(key);
        System.out.println("redisUtils里面，tokenFromRedis的值："+tokenFromRedis);
        JSONArray jsonArray = JSON.parseArray(tokenFromRedis);*/
        //System.out.println("@@@@@@@@@@@@@@@@@@utils里面,追加之前:"+jsonArray);
        if(jsonArray==null){
            jsonArray = new JSONArray();
        }
        boolean add = jsonArray.add(obj);
        //System.out.println("@@@@@@@@@@@@@@@@@@utils里面,追加之后:"+jsonArray);
        if(add){
            redisTemplate.opsForValue().set(KeyValueContent.TOKEN_USER_PREFIX + key,jsonArray,expire,TimeUnit.DAYS);
        }
    }


}
